import { Detail } from 'detail-model.js';

var detail = new Detail();
Page({
	data: {
		goods: {},
    data:{},
		current: 0,
		galleryHeight: getApp().screenWidth,
    currentTab: [],
    flag: true,
    flag1: true,
    selected:[],
    quantity: 1,//所选商品数量
    imgUrl:'',
    selectednum:'',
    price:'',
    products_id:'',//商品id
    specifications:[],
    buyButtonTab: true,
    specif_id:'',//用户所选商品的规格
    evaluate:[],
    id:''
	},
  onLoad: function (options) {
    var goodsId = options.objectId;
    this._loadData(goodsId);
  },
  _loadData: function (goodsId,callback) {
    var that = this;
    //获得product信息
    detail.getProductDetail(goodsId,(data) => {
      that.initData(data['product'][0]['speci']);
      that.setData({
        id: data['product'][0]['products_id'],
        goods: data['product'][0],
        data: data['product'][0]['speci'],
        imgUrl: data['product'][0]['recommend'],
        price: data['product'][0]['products_sellingprice'],
        products_id: data['product'][0]['products_id'],
        specifications: data['product'][0]['specifications'],
        count:data['count'],
        evaluate: data['evaluate']
      });
    });
    
  },
  previewImage: function (e) {
    wx.previewImage({
      //从<image>的data-current取到current，得到String类型的url路径
      current: e.currentTarget.dataset.current,
      urls: [e.currentTarget.dataset.current] // 需要预览的图片http链接列表
    })
  },
  initData: function (data) {
    var currentTab = [];
    var selected = [];
    //console.log(data)
    for (var i = 0; i < data.length; i++) {
      currentTab[i] = []
       for (var j = 0; j < data[i].pspecifications.length; j++) {
         currentTab[i].push(0)
       }
    }
    for (var i = 0; i < data.length; i++) {
      selected.push("");
    }
    this.setData({
      currentTab: currentTab,
      selected: selected
    });
    console.log(this.data.currentTab)
  },
  screenTap: function (e) {
    var Index1 = e.currentTarget.dataset.indexo;
    var Index2 = e.currentTarget.dataset.idx;
    var currentTab = this.data.currentTab
    console.log(currentTab)
    for (var j = 0; j < currentTab[Index1].length; j++) {
      if (j == Index2) {
        this.data.currentTab[Index1][j] = 1;
      } else {
        this.data.currentTab[Index1][j] = 0;
      }
    }
    console.log(this.data.currentTab);
    this.data.selected[Index1] = e.currentTarget.dataset.id
    console.log(this.data.selected)
    var imgUrl = e.currentTarget.dataset.imgurl
    if (imgUrl != "") {
      this.setData({
        imgUrl: imgUrl
      })
    } else {
      this.setData({
        imgUrl: this.data.imgUrl
      })
    }
    this.setData({
      currentTab: this.data.currentTab,
      selected: this.data.selected
    });
    //先判断是否都选择了
    if (this.data.selected.length == currentTab.length){
      console.log(this.data.selected)
      //集合是否有对应的
      specifications: []
      for (var i = 0; i < this.data.specifications.length; i++)
      {
        if (JSON.stringify(this.data.selected) == JSON.stringify(this.data.specifications[i]['pspeci_element']))
            {
              
             this.getIsStock(this.data.specifications[i]['pspeci_id']);  
              //console.log(res); 
            }
      }
      
    }
  },
  //查询是否有库存及填充页面
  getIsStock: function (id,callback) {
    var that = this;
    detail.getIsStock(id, (data) => {
      console.log(data);
      //填写价格
      if (data) {
        this.setData({
          price: data['pspeci_price'],
          specif_id: data['pspeci_id']
        })
        
        //判断库存
        if (!data['pspeci_stock']) {
          //展示售罄
          this.setData({
            buyButtonTab: false
          })
        }else
        {
          this.setData({
            buyButtonTab: true
          })
        }
      }
    });
  },
  //添加购物车
  addCart: function () {
    if (this.data.specif_id == "") {
      this.setData({ flag: false })
      wx.showToast({
        title: '请选择规格',
        icon: 'success',
        duration: 1000
      });
      return;
    }
    var   cartData={
      "products_id": this.data.products_id,
      "spe_id": this.data.specif_id,
      "num": this.data.quantity
    };
    console.log(cartData);
    this.insertCart(cartData);
  },
  insertCart: function (cartData)
  {
    detail.AddCart(cartData,(data) => {
        console.log(data); 
        if(data)
      {
          //返回状态表示添加成功
          this.showCartToast();
      } else if(data['errorCode']==10001)
        {
          wx.showToast({
            title: '加入购物车失败',
            icon: 'success',
            duration: 1000
          });
          return;
        }
    });
  },
  //去付款
goPay:function()
{
  if (this.data.specif_id == "") {
    this.setData({ flag: false })
    return;
  }
  var cartData = {
    "products_id": this.data.products_id,
    "spe_id": this.data.specif_id,
    "num": this.data.quantity
  };
  this.createOrder(cartData);
},
createOrder:function(cartData)
{
  //提交跳转页面
  detail.createOrder(cartData, (data) => {
    if (data) 
    {
      //返回状态表示添加成功
      this.goOrderx(data);
    } else if (data['errorCode'] == 10001) 
    {
      console.log(data['msg']);
    }
  });
},
goOrderx: function (cartId) {
  wx.navigateTo({
    url: '../../order/checkout/checkout?cartIds=' + cartId,
  });
},
  showCartToast: function () {
    wx.showToast({
      title: '已加入购物车',
      icon: 'success',
      duration: 1000
    });
  },
  showCart: function () {
    wx.switchTab({
      url: '../../cart/cart'
    });
  },
  /**
   * 弹出层函数
   */
  //出现
  show: function () {
    this.setData({
       flag: false 
       })
  },
  //消失
  hide: function () {
    this.setData({ 
      flag: true
       })
  },
  show1: function () {
    this.setData({ flag1: false })
  },
  hide1: function () {
    this.setData({
      flag1: true
    })
  },
  bindMinus: function (e) {
    var num = this.data.quantity;
    if (num > 1) {
      num--;
    }
    this.setData({
      quantity: num,
      selectednum:"x"+num,
    });
  },
  bindPlus: function (e) {
    var num = this.data.quantity;
    num++;
    this.setData({
      quantity: num,
      selectednum: "x" + num
    });
  }, 
  sellOutTap: function (e) {
    wx.showToast({
      title: '此规格已售罄',
      icon: 'none',
      duration: 1000
    });
  },
  toHome: function (e) {
    wx.switchTab({
      url: "../../index/index"
    });
  },
  tapEvaluate: function () {
    
    var id=this.data.id;
    wx.navigateTo({
      url: "../evaluate/evaluate?id="+id
    });
  },
});